package com.techgene.kanban.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.techgene.kanban.controller.LoginLogoffController;
import com.techgene.kanban.dao.LoginDao;
import com.techgene.kanban.domain.User;
import com.techgene.kanban.exception.KBDaoException;
import com.techgene.kanban.exception.KBServiceException;
import com.techgene.kanban.service.LoginService;
import com.techgene.kanban.util.AppConstants;

@Service
public class LoginServiceImpl implements LoginService {

	private Logger logger = LoggerFactory.getLogger(LoginLogoffController.class);

	@Autowired
	LoginDao loginDao;
	@Autowired
	private PlatformTransactionManager txManager;

	
	
	
	/**
	 * validate User
	 * 
	 * @param userName
	 * @param password
	 * @throws KBServiceException
	 * @throws KBDaoException
	 */
	public User validateUser(String username, String password)throws KBServiceException, KBDaoException {
		
		logger.debug(">> validateUser [username ={}, password ={} ]", username,password);
		User user = null;
		/* start of transaction */
		TransactionDefinition def = new DefaultTransactionDefinition();
		TransactionStatus status = txManager.getTransaction(def);
		
		try {

			/*
			 * calling finduserByUsername in loginDao implemented class to validate user
			 */
			user = loginDao.findUserByUsername(username, password);
			logger.debug("user ={}", user);
			/* commit */
			txManager.commit(status);

		} 
		
		catch (KBDaoException e) {
			
			/* rollback */
			txManager.rollback(status);
			throw new KBServiceException(e.getErrorCode(), e.getMessage(), e);

		} 
		
		catch (Exception e) {
			
			/* rollback */
			txManager.rollback(status);
			throw new KBServiceException(AppConstants.ERROR.SERVICE_UNKNOWN_ERROR_VALIDATING_USER.code,AppConstants.ERROR.SERVICE_UNKNOWN_ERROR_VALIDATING_USER.msg,e);

		} 
		
		catch (Throwable e) {
			
			/* rollback */
			txManager.rollback(status);
			throw new KBServiceException(AppConstants.ERROR.SERVICE_UNKNOWN_ERROR_VALIDATING_USER.code,AppConstants.ERROR.SERVICE_UNKNOWN_ERROR_VALIDATING_USER.msg,e);

		}

		logger.debug("<< validateUser , user = {} " , user);
		return user;
	}

}
